/*
 * jquery.flickrutils.js
 *
 * Copyright (C) 2009 - Antonio Perez-Aranda Alcaide ant30tx@gmail.com
 *
 * <program name> is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * <program name> is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with <program name>; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, 
 * Boston, MA  02110-1301  USA
 */
 
 

var API_KEY = "22d7d7597a2d284e0e109dc042cb8c25";
var console;
if (!window.console){
    console = {
        warn:function(m){},
        log:function(m){}
    }
}

(function($){

    var queryToflickr = function(command, callback, params){
        if (!params) params = {}; 
        url = 'http://api.flickr.com/services/rest/?format=json&jsoncallback=?&api_key='+s.flickr_key+'&method='+command;
        $.getJSON(url, params, function (response) {
            if (response.stat != "ok"){
                console.log("some errors: " + response.message);
            }            else if (callback) callback(response);
        });
    };

    var getRawPhotoURL = function(photo, size){
        /*http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpg*/
        return "http://farm" + photo.farm + ".static.flickr.com/" +  photo.server + "/" + photo.id + "_" + photo.secret + "_"+size+".jpg";
    };

    var getPublicPhotoViewURL = function(photo, userid){
        /*http://www.flickr.com/photos/{user-id}/{photo-id}*/
        return "http://www.flickr.com/photos/"+userid+"/"+photo.id;
    };


    $.fn.loadflickrpicker = function(options){
        var s = {
            per_page:7,
            callback: function () {console.warn("callback not defined on loadflickrpicker")}
        };
        if(options) $.extend(s, options);
        var initial_values = $(this).attr("value").split(",");

        var searchtext_selector = "#photosearcherform input[name=searchtext]";
        var userid_selector = "#photosearcherform input[name=userid]";
        var username_selector = "#photosearcherform input[name=username]";

        var userid = null;
        var usrname = null;

        var flickerpickedhtml = '\
<div id="flickrpicked">\
  <div id="flickrbackground"></div>\
  <div id="flickrwrapper">\
    <h1>Flickr Picker</h1>\
    <form id="photosearcherform" class="photosearcher">\
    <ul>\
      <li>\
          <label>Search Text:</label>\
          <input name="searchtext" type="text"/>\
      </li>\
      <li>\
          <label>User ID:</label>\
          <input name="userid" type="text" value=""/>\
      </li>  \
      <li>\
          <label>User Name:</label>\
          <input name="username" type="text" value="ant30"/>\
      </li>  \
    </ul>\
    <div class="actions"> \
      <input type="button" name="search" value="Search">\
      <input type="button" name="all" value="Recent Photos">\
      <input type="button" name="previous" value="Previous Page"/>\
      <input type="button" name="nextpage" value="Next Page"/>\
    </div>\
    </form>\
    <div class="helptext">\
        <p>Ti pick any image, click on image, then if you need to delete some image from selected, click on it</p>\
        <p>Click with middle button to see image at flickr web</p>\
        <p>Change user if you need to select any other user. Only full public content are visible</p>\
        <p></p>\
    </div>\
    <div class="clear"></div>\
    <h2>Seach Results</h2>\
    <div id="searchresults" class="photolist">\
        <div class="photosslide"></div>\
    </div>\
    <div class="clear"></div>\
    <h2>Picked Photos</h2>\
    <div id="picked" class="photolist">\
        <div class="photosslide">\
            <ul>\
            </ul>\
        </div>\
    </div>\
    <div class="clear"></div>\
    <div class="controlactions">\
        <input type="button" name="savepicked" value="Save picked"/>\
        <input type="button" name="cancel" value="Cancel"/>\
    </div>\
  </div>\
</div>\
';

        $("body").append(flickerpickedhtml);

        $.fn.flickrPhotoList = function (options){
            var s = { size: 's',
                      photos: null};
            if(options) $.extend(s, options);
            this.empty();
            var list = $("<ul>").appendTo(this);
            if (!s.photos){
                this.append("no hay resultados");
            }
            $.each(s.photos.photo, function(i,photo){
                public_view = getPublicPhotoViewURL(photo, userid);
                raw_image = getRawPhotoURL(photo, s.size);
                li = $("<li>");
                link = $("<a>");
                link.attr("href", public_view);
                link.attr("rel", photo.id);
                img = $("<img>");
                img.attr("src", raw_image);
                img.appendTo(link);
                if (li.draggable){
                    li.draggable({ opacity: 0.35, connectToSortable: '#picked .photosslide ul', revert: true });
                }
                link.click(function(){
                    image_id = $(this).attr('rel');
                    newlink = $(this).clone();
                    if (!$("#"+image_id).length){
                        newlink.attr('id', image_id);
                        newli = $("<li>");
                        
                        newlink.click(function(){
                            $(this).remove();
                            return false;
                        });
                        
                        newlink.appendTo(newli);
                        newli.appendTo($("#picked ul"));
                    }
                    
                    return false;
                });
                link.appendTo(li);
                li.appendTo(list);

            });
            return this;
        };
        
        var findByUsername = function(username){
            queryToflickr("flickr.people.findByUsername", 
                           findByUsername_response,
                           {username:username})
        }
 
        var findByUsername_response = function(response){
            userid = response.user.id;
            $(userid_selector).attr("value", userid);
            listing_function();
        }
 
        var getPublicPhotos = function(page){
            queryToflickr("flickr.people.getPublicPhotos",
                           getPublicPhotos_response,
                           {user_id: userid,
                            per_page: s.per_page,
                            page: page});
        }

        var getPublicPhotos_response = function(response){
            $("#flickrpicked #searchresults .photosslide").flickrPhotoList({photos: response.photos});
        }

        var photos_search = function(params){
            queryToflickr("flickr.photos.search",
                           photos_search_response,
                           params);
        }

        var photos_search_response = function(response){
            $("#flickrpicked #searchresults .photosslide").flickrPhotoList({photos: response.photos});
        }

        var page = 1;

        flickr_search = function(){
            filter = {user_id: userid,
                      per_page: s.per_page,
                      page: page};
            
            var searchname = $(searchtext_selector).attr('value');
            
            if (searchname){
                filter.text = searchname;
            }
            photos_search(filter);

        }
        
        all_photos = function(){
            getPublicPhotos(page);
        }
    
        $("#flickrpicked input[name=all]").click(function() {
            page = 1;
            listing_function = all_photos;
            listing_function();
        });
        
        $("#flickrpicked input[name=search]").click(function () {
            page = 1;
            listing_function = flickr_search;
            listing_function();
        });

        $(searchtext_selector).change(function(){
            page = 1;
            listing_function = flickr_search;
            listing_function();
        });

        $(userid_selector).change(function(){
            userid = $(this).attr('value');
            all_photos();
        });

        $(username_selector).change(function(){
            username = $(this).attr('value');
            if (!userid){
                findByUsername(username);
            }
        });



        $("#flickrpicked input[name=nextpage]").click(function() {
            page++;
            listing_function();
        });

        $("#flickrpicked input[name=previouspage]").click(function() {
            if (page){
                page--;
                listing_function();
            }
        });

        $(userid_selector).change(function() {
            userid = $(this).attr('value');
        });

        $(username_selector).change(function() {
            findByUsername($(this).attr('value'));
        });

        var listing_function = all_photos;

        userid = $(userid_selector).attr('value');
        username = $(username_selector).attr('value');
        if (!userid){
            findByUsername(username);
        }
        $("#flickrpicked input[name=savepicked]").click(function(){
            var photos_id = []
            $("#picked a").each(function (i, e){
                anotherid = $(e).attr('rel');
                photos_id[i] = anotherid;
            });
            s.callback(photos_id);
            $("#flickrpicked").remove();
       });
       $("#flickrpicked input[name=cancel]").click(function(){
            var photos_id = []
            $("#picked a").each(function (i, e){
                anotherid = $(e).attr('rel');
                photos_id[i] = anotherid;
            });
            s.callback(initial_values);
            $("#flickrpicked").remove();
       });
    };
    
    
    $.fn.flickrpicker = function(options){
         s = {flickr_key: API_KEY,
              callback: function (values){
                            $("input[name=result]").attr("value", values);
                        }
             };
        if(options) $.extend(s, options);
        this.click(function () {
            if (!$("#flickrpicked").length){
                $(this).loadflickrpicker(s);
            }
        });
        $(this).addClass("flickr");
        return this;
    }; 


//"3154251101,3154255229"

      var createImgFromPhoto = function(photo, s){
            
            var public_view = getPublicPhotoViewURL(photo, photo.owner.nsid);
            var raw_image = getRawPhotoURL(photo, s.size);
            var e2 = $(s.element2);
            link = $("<a>");
            link.attr("href", public_view);
            link.attr("rel", photo.id);
            if (s.linkattrs){
                link.attr(s.linkattrs)
            }
            img = $("<img>");
            img.attr("src", raw_image);
            if (s.imgattrs){
                img.attr(s.imgattrs)
            }

            img.appendTo(link);
            link.appendTo(e2);
            return $(e2);
        };  


    $.fn.loadflickrimageslist = function(options){

        var s = {
             flickr_key: "22d7d7597a2d284e0e109dc042cb8c25",
             photo_ids: "",
             element1:"<ul>",
             element2:"<li>",
             linkattrs:null,
             imageattrs:null,
             size: 'm'
             };
        if(options) $.extend(s, options);
        photo_ids = photo_ids.split(",");

        var retrievephotoinfo = function(photo_id){
            queryToflickr("flickr.photos.getInfo", retrievephotoinfo_response, {photo_id:photo_id});
        }
        e1 = $(s.element1);
        e1.appendTo(this);
        var retrievephotoinfo_response = function(response){
            if (response.photo){
                item = createImgFromPhoto(response.photo, s);
                item.appendTo(e1);
            }
        }
        
        $.each(photo_ids, function(i, photo_id){
            retrievephotoinfo(photo_id);
        });
        
        return this;
    }
    
    $.fn.loadflickrimage = function(options){
        var s = {
             flickr_key: API_KEY,
             imageattrs:null,
             size: 'm'
             };
        if(options) $.extend(s, options);
        photo_id = $(this).attr("rel");
        var locate = $(this);
        var retrievephoto_response = function(response){
            if (response.photo){
                photo = response.photo;
                var public_view = getPublicPhotoViewURL(photo, photo.owner.nsid);
                var raw_image = getRawPhotoURL(photo, s.size);
                img = $('<img>');
                img.attr("src", raw_image);
                if (s.imgattrs){
                    img.attr(s.imgattrs)
                }
                locate.attr("href", public_view);
                img.appendTo(locate);
            }
        }
        queryToflickr("flickr.photos.getInfo", retrievephoto_response, {photo_id:photo_id});        
        return $(this);
    }

    $.fn.loadflickrallimages = function(options){
        var s = {
             flickr_key:API_KEY,
             imageattrs:null,
             size: 'm',
             largesize: 'b'
             };
        if(options) $.extend(s, options);
        
        photos = $("a.flickrid");
        
        var retrievephoto_response = function(response){
            if (response.photo){
                var photo = response.photo;
                var public_view = getPublicPhotoViewURL(photo, photo.owner.nsid);
                var raw_image = getRawPhotoURL(photo, s.size);
                var large_raw_image = getRawPhotoURL(photo, s.largesize);
                links = $("a."+response.photo.id);
                $.each(links, function(i, l){
                    if ($(l).hasClass("raw")){
                        $(l).attr("href", large_raw_image);
                    }
                    else {
                        $(l).attr("href", public_view);
                    }
                })

                img = $("<img>");
                img.attr("src", raw_image);
                if (s.imgattrs){
                    img.attr(s.imgattrs)
                }
                img.appendTo(links);
                }
        }

        var retrievephoto = function(photo_id, photo){
            queryToflickr("flickr.photos.getInfo", retrievephoto_response, {photo_id:photo_id});
        }

        var getphotoid = function (photo){
            classes = $(photo).attr('class');
            classes = classes.split(" ");
            for(var i = 0; i<classes.length; i++){
                if (parseInt(classes[i])) return classes[i]
            }
        }

        var ids = {};
        photos.each(function(i, photo){
            var flickrid = getphotoid(photo);
            if (!ids[flickrid]) {
                ids[flickrid] = true;
                retrievephoto(flickrid);
            }
                
        });

        return $(this);
    }
    
})(jQuery);
